import { Application } from "egg";
import CodoBase from "../../CodoBase";
import { hc } from "../hc";


export default class BaseHttpService extends CodoBase {
    constructor(protected device: hc.http.machine, protected app: Application, private options?: { useHttps?: boolean }) {
        super(app)
    }

    /** 发送请求到设备 */
    async request<T = any>(operator: string, data: any): Promise<T> {
        const { ip } = this.device;
        const protocol = this.options?.useHttps ? `https` : `http`
        const url = `${protocol}://${ip}/action/${operator}`;
        data = Object.assign({ operator: operator }, data);

        try {
            this.app.logger.debug("[hc_curl] 请求海清机器的操作url： %j", url);
            const res = await this.curl(url, {
                method: "POST",
                headers: {
                    // "Transfer-Encoding": "chunked",
                    // "Content-Length": "",
                },
                timeout: [30000, 30000],
                contentType: "json",
                dataType: "json",
                auth: this.device.user,
                data,
            });
            // console.log(res);
            if (res.status >= 200 && res.status <= 304) {
                return res.data;
            } else {
                this.app.logger.error("[hc_curl] 卡机设备：%j 响应的状态异常： %j", ip, res);
                throw new Error(`响应状态异常 ${res.status} ${JSON.stringify(res.data)}`);
            }
        } catch (error) {
            this.app.logger.error("[hc_curl] 卡机设备：%j 请求时或解析结果时出错： %j", ip, (error as any).message);
            throw error;
        }
    }

}